#include "http.hpp"

std::string RequestStr(const HttpRequest &req)
{
    std::stringstream ss;
    ss << req._method << " " << req._path << " " << "HTTP/1.1\r\n";
    for (auto &it : req._params)
    {
        ss << it.first << ": " << it.second << "\r\n";
    }
    for (auto &it : req._headers)
    {
        ss << it.first << ": " << it.second << "\r\n";
    }
    ss << "\r\n";
    ss << req._body;
    return ss.str();
}
void Hello(const HttpRequest &req, HttpResponse *rsp)
{
    rsp->SetContent(RequestStr(req), "text/plain");
}
void Login(const HttpRequest &req, HttpResponse *rsp)
{
    std::string body = req._body;
    int end = body.find("&");
    int begin = body.find("=") + 1;
    std::string username = body.substr(begin, end - begin);
    begin = body.find("=", begin);
    std::string password = body.substr(begin + 1);
    if(username == "20231170194" && password == "123456")
    {
        std::string body;
        Util::ReadFile("./wwwroot/LoginSuccess.html", &body);
        rsp->SetContent(body, "text/html");
    }
    else
    {
        std::string body;
        Util::ReadFile("./wwwroot/LoginFail.html", &body);
        rsp->SetContent(body, "text/html");
    }
    
}
void PutFile(const HttpRequest &req, HttpResponse *rsp)
{
    rsp->SetContent(RequestStr(req), "text/plain");
}
void DeleteFile(const HttpRequest &req, HttpResponse *rsp)
{
    rsp->SetContent(RequestStr(req), "text/plain");
}
#define WWWROOT "./wwwroot/"
int main()
{
    HttpServer server(8080);
    server.SetThreadCount(3);
    server.SetBasDir(WWWROOT); // 设置静态资源根目录，告诉服务器有静态资源请求到来，需要到哪里去找资源文件
    server.Get("/hello", Hello);
    server.Post("/login", Login);
    server.Delete("/1234.txt", DeleteFile);
    server.Put("/1234.txt", PutFile);
    server.Lsiten();
    return 0;
}